import hashlib
import os
import time

from flask import jsonify, request, session, render_template, redirect, url_for

from models import db
from models.index import User, Follow
from . import user_bp


@user_bp.route("/user/follow", methods=["POST"])
def follow():
    action = request.json.get('action')
    news_author_id = request.json.get('user_id')
    user_id = session.get('user_id')
    if action == 'do':

        news_author = db.session.query(User).filter(User.id == news_author_id).first()
        if not user_id:
            return jsonify(
                {
                    'errno': 3002,
                    'errmsg': '请先登录'
                }
            )
        if user_id in [x.id for x in news_author.followers]:
            return jsonify(
                {
                    'errno': 3001,
                    'errmsg': '已经关注啦'
                }
            )

        try:
            follow = Follow(followed_id=news_author_id, follower_id=user_id)
            db.session.add(follow)
            db.session.commit()

            ret = {
                'errno': 0,
                'errmsg': '关注成功'
            }

            return jsonify(ret)


        except Exception as ret:
            ret = {
                "errno": 3003,
                "errmsg": "关注失败..."
            }

            return jsonify(ret)
    else:

        try:
            follow = db.session.query(Follow).filter(
                Follow.followed_id == news_author_id, Follow.follower_id == user_id).first()
            db.session.delete(follow)
            db.session.commit()
            ret = {
                'errno': 0,
                'errmsg': '取消关注成功'
            }
            return jsonify(ret)
        except Exception as e:
            db.session.rollback()
            ret = {
                'errno': 3004,
                'errmsg': '取消关注失败'

            }

            return jsonify(ret)


@user_bp.route('/user/user_center')
def user_center():
    user_id = session.get('user_id')
    if user_id:

        user = db.session.query(User).filter(User.id == user_id).first()

        return render_template('index/user.html', user=user)
    else:
        return redirect(url_for('index.index'))


@user_bp.route("/user/user_base_info")
def user_base_info():
    user_id = session.get('user_id')
    if user_id:
        user = db.session.query(User).filter(User.id == user_id).first()

        return render_template("index/user_base_info.html", user=user)
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/user/basic', methods=['GET', 'POST'])
def user_basic():
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    user_id = session.get('user_id')
    user = db.session.query(User).filter(User.id == user_id).first()

    if not user:
        ret = {
            'errno': 4002,
            'errmsg': '没有此用户'
        }
        return jsonify(ret)

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    db.session.commit()

    ret = {
        'errno': 0,
        'errmsg': '修改成功'
    }
    return jsonify(ret)


@user_bp.route("/user/user_pass_info")
def user_pass_info():
    user_id = session.get('user_id')
    if user_id:
        return render_template("index/user_pass_info.html")
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/user/password', methods=['GET', 'POST'])
def user_password():
    new_password = request.json.get('new_password')
    old_password = request.json.get('old_password')

    user_id = session.get('user_id')

    if not user_id:
        return jsonify(
            {
                'errno': 4001,
                'errmsg': '请先登录'
            }
        )

    user = db.session.query(User).filter(User.id == user_id, User.password_hash == old_password).first()
    if user:
        user.password_hash = new_password
        db.session.commit()
        session.clear()
        ret = {
            'errno': 0,
            'errmsg': '修改密码成功,请重新登录'
        }

    else:
        ret = {
            'errno': 4004,
            'errmsg': '原密码错误'
        }

    return jsonify(ret)


@user_bp.route("/user/user_pic_info.html")
def user_pic_info():
    user_id = session.get("user_id")
    if user_id:
        user = db.session.query(User).filter(User.id == user_id).first()
        return render_template("index/user_pic_info.html", user=user)


@user_bp.route("/user/avatar", methods=['GET', 'POST'])
def user_avatar():
    f = request.files.get("avatar")
    user_id = session.get("user_id")
    if f and user_id:
        user = db.session.query(User).filter(User.id == user_id).first()
        # 为了防止多个用户上传的图片名字相同，需要将用户的图片计算出一个随机的用户名，防止冲突
        file_hash = hashlib.md5()
        file_hash.update((f.filename + time.ctime()).encode("utf-8"))
        file_name = file_hash.hexdigest() + f.filename[f.filename.rfind("."):]

        if user.avatar_url:
            os.remove('./static/upload/' + user.avatar_url)
        # 保存图片信息到数据库
        user.avatar_url = file_name
        db.session.commit()

        file_name = "./static/upload/" + file_name
        # 用新的随机的名字当做图片的名字
        f.save(file_name)
        # 修改数据库中用户的头像链接（注意，图片时不放在数据库中的，数据库中存放的图片的名字或者路径加图片名）

        ret = {
            "errno": 0,
            "errmsg": "成功"
        }
    else:
        ret = {
            "errno": 4003,
            "errmsg": "上传失败"
        }

    return jsonify(ret)
